#Python parser for adding test code
import sys

try:
	#File containing the code
    filepath = sys.argv[1]
except IndexError:
	sys.exit(2)

try:
	#File which will be written to
	debugfile = sys.argv[2]
except IndexError:
	sys.exit(2)

openingtag = 0
functionname = ''

def DoIt():
	global filepath
	#Reading the entire file
	infile = open(filepath, 'r')
	lines = infile.readlines()
	infile.close()
	#Opening write stream
	with open(filepath, 'w') as outfile:
		i = 0
		for line in lines:
			outfile.write( line )
			if CheckLine( lines, i ):
				outfile.write( InsertDebugCode(filepath, i, lines) )
			i += 1
		outfile.close()

def CheckLine(lines, i):
	newfunc = False
	global openingtag

	pos = lines[i].strip().find('{')
	while pos > -1: #looping because there might be more than one '{'
		if openingtag == 0 \
		and lines[i].find('}') == -1 \
		and lines[i].find('struct') == -1 \
		and lines[i].find('=') == -1 \
		and lines[i].find('#define') == -1 \
		and lines[i].find('\\') == -1:
			newfunc = True
		openingtag += 1
		pos = lines[i].strip().find('{', pos+1)

	pos = lines[i].find('}')
	while pos > -1: #looping because there might be more than one '}'
		openingtag -= 1
		pos = lines[i].find('}', pos+1)

	return newfunc

def InsertDebugCode(filename, i, lines):
	global debugfile
	
	fname = filename.rsplit('/', 1)
	
	
	line  = '    /* <!-- BEGIN DEBUG */\n'
	line += '    FILE *ffile;\n'
	line += '    ffile = fopen("{0}","a+");\n'.format(debugfile)
	line += '    fprintf(ffile,"%25s: %s\\n","{0}", "{1}"); /*writes*/\n'.format(fname[len(fname)-1], FindFuncName(lines, i))
	line += '    fclose(ffile); /*done!*/\n'
	line += '    /* END DEBUG --> */\n'
	return line

def FindFuncName(lines, i):
	_i = i
	while _i > -1:
		pos2 = lines[_i].strip().find('(')		
		if  pos2 > -1:
			pos1 = lines[_i].strip().rfind(' ', 0, pos2)+1
			
			if pos1 > -1:
				break
			if pos2 > 0:
				pos1 = 0
				break
			else:
				pos1 = lines[_i-1].rfind(' ')
				pos2 = len(lines[_i-1])-1
				break
		_i -= 1

	return lines[_i][pos1:pos2]

def RemoveDebugCode():
	global filepath
	dontwrite = False
	#Reading the entire file
	infile = open(filepath, 'r')
	lines = infile.readlines()
	infile.close()
	#Opening write stream
	with open(filepath, 'w') as outfile:
		for line in lines:
			if line.find('<!-- BEGIN DEBUG') > -1:
				dontwrite = True
			if not dontwrite:
				outfile.write( line )	
			if line.find('END DEBUG -->') > -1:
				dontwrite = False

if debugfile == 'remove':
	RemoveDebugCode()
else:
	DoIt()
